<template>
    <div>
        <el-dialog
                title="添加分类"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="handleClose">
            <el-form status-icon :model="categoryForm" label-width="100px" class="demo-ruleForm login_form" :rules="rules" ref="ruleForm">
                <div>
                    <el-form-item label="类别编号：" prop="id" >
                        <el-input v-model="categoryForm.id" clearable placeholder="1—4位数字，唯一" maxlength="4"></el-input>
                    </el-form-item>
                    <el-form-item label="类别名称：" prop="name">
                        <el-input placeholder="不大于10个汉字" v-model="categoryForm.name" clearable maxlength="20" ></el-input>
                    </el-form-item>
                    <el-form-item label="类别描述：" prop="describe" >
                        <el-input
                                type="textarea"
                                :autosize="{ minRows: 2, maxRows: 5}"
                                placeholder="简单描述一下此类别（可选，不大于50个汉字）"
                                v-model="categoryForm.describe">
                        </el-input>
                    </el-form-item>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="add('ruleForm')">添 加</el-button>
            </span>
        </el-dialog>

        <el-row>
            <h1 class="center">分类管理</h1>
        </el-row>
        <el-row class="add_btn">
            <el-col :span="2" :offset="14">
                <el-button type="primary" size="medium" @click="dialogVisible = true">添加</el-button>
            </el-col>
        </el-row>

        <!--贴吧类别 列表-->
        <el-row type="flex" justify="center">
            <el-col :span="18">
                <el-table
                        :data="list"
                        class="list">
                    <el-table-column
                            label="类别编号"
                            width="150"
                            prop="id">
                    </el-table-column>
                    <el-table-column
                            label="类别名称"
                            width="180"
                            prop="name">
                    </el-table-column>
                    <el-table-column
                            label="类别描述"
                            width="450"
                            prop="describe">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button
                                    size="mini"
                                    @click="handleEdit(scope.row.id)">编辑</el-button>
                            <el-popconfirm title="确定删除该分类吗？" v-on:confirm="handleDelete(scope.row.id)">
                                <el-button
                                        slot="reference"
                                        size="mini"
                                        type="danger">删除</el-button>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    export default {
        name: "classify",
        data(){
            var checkIfIdUsed = (rule, value, callback) => {
                /*检测分类编号是否已被使用*/
                // this.$http.get("http://localhost:8081/category/idUsed?&id=" + this.categoryForm.id).then(req=>{
                this.$http.get(this.GLOBAL.serverBaseUrl + this.GLOBAL.categoryIdUsed + "?id=" + this.categoryForm.id).then(req=>{
                    if (req.data.result_code === 200){
                        callback();
                    }else{
                        callback(new Error(req.data.msg));
                    }
                });
            };
            return{
                list: [],  /*已有分类列表*/
                categoryForm: {  /*分类表单*/
                    id: '',
                    name: '',  /*类别名称*/
                    describe: '',
                },
                rules: {
                    id: [
                        { required: true, message: '请输入类别编号', trigger: 'blur' },
                        { validator: checkIfIdUsed, trigger: 'blur' }  /*检验该类别id 是否已被使用*/
                    ],
                    name: [
                        { required:true, message: '请输入类别名称', trigger: 'blur'}, /*在失去焦点时触发*/
                    ],
                },
                dialogVisible: false,  /*添加分类模态框  默认不显示*/

            }
        },
        created(){  /*加载页面时执行 显示已有的分类列表*/
            // this.$http.get("http://localhost:8081/category/getList").then(req=>{
            this.$http.get(this.GLOBAL.serverBaseUrl + this.GLOBAL.categoryGetList).then(req=>{
                if (req.data !== ""){
                    if (req.data.rs.result_code === 200){ /*查询成功   */
                        this.list = req.data.list;
                    }else {  /*查询失败*/
                        this.$message({
                            showClose: true,
                            duration: 5000, /*默认5秒后自动关闭， 用户也可手动关闭*/
                            message: req.data.rs.msg,
                            type: 'error'
                        });
                    }
                }else {
                    this.$message.error('糟糕，服务器出事了。。');
                }
            })


        },
        methods:{
            clearCategoryForm(){ /*清空categoryForm(添加类别时的表单)   一般在添加类别时 点击取消或者关闭键*/
                this.categoryForm.id = '';
                this.categoryForm.name = '';
                this.categoryForm.describe = '';
            },
            handleEdit(id){
                console.log("（来自编辑）类别id：" + id);
            },
            /*删除一个分类*/
            handleDelete(id){
                // this.$http.get("http://localhost:8081/category/del?id=" + id).then(req=>{
                this.$http.get(this.GLOBAL.serverBaseUrl + this.GLOBAL.categoryDel + "?id=" + id).then(req=>{
                    if (req.data !== ""){
                        if (req.data.result_code === 200){ /*添加成功   提示成功并刷新页面*/
                            this.$router.push({name:'classifytmp', params:{fromClassify: 'fromClassify'}});
                            this.$message({
                                showClose: true,
                                duration: 5000, /*默认5秒后自动关闭， 用户也可手动关闭*/
                                message: req.data.msg,
                                type: 'success'
                            });
                        }else {  /*添加失败*/
                            this.$message({
                                showClose: true,
                                duration: 5000, /*默认5秒后自动关闭， 用户也可手动关闭*/
                                message: req.data.msg,
                                type: 'error'
                            });
                            this.dialogVisible = false;  /*关闭对话框*/
                        }
                    }
                });
                console.log("(来自删除)类别id：" + id);
            },
            add(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        var formData = new FormData();
                        formData.append("id", this.categoryForm.id);
                        formData.append("name", this.categoryForm.name);
                        formData.append("describe", this.categoryForm.describe);

                        // this.$http.post("http://localhost:8081/category/add", formData).then(req=>{
                        this.$http.post(this.GLOBAL.serverBaseUrl + this.GLOBAL.addCategoryUrl, formData).then(req=>{
                            if (req.data !== ""){
                                if (req.data.result_code === 200){ /*添加成功   提示成功并刷新页面*/
                                    // location.reload(); /*刷新本页面（载入最新的分类列表）*/
                                    this.$router.push({name:'classifytmp', params:{fromClassify: 'fromClassify'}});
                                    // location.href = "/#/index";
                                    // this.$router.go(0); //刷新当前页面
                                    this.$message({
                                        showClose: true,
                                        duration: 5000, /*默认5秒后自动关闭， 用户也可手动关闭*/
                                        message: '分类添加成功！',
                                        type: 'success'
                                    });
                                }else {
                                    this.$message({
                                        showClose: true,
                                        duration: 5000, /*默认5秒后自动关闭， 用户也可手动关闭*/
                                        message: req.data.msg,
                                        type: 'error'
                                    });
                                    this.dialogVisible = false;  /*关闭对话框*/
                                }
                            }else {
                                this.$message.error('糟糕，服务器出事了。。');
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            handleClose(done) {
                this.$confirm('确认关闭？关闭将清空已填信息。')
                    .then(() => {
                        this.clearCategoryForm(); //清空已填写的内容
                        done();
                    })
                    .catch(() => {});
            },

        }
    }
</script>

<style scoped>
    h1{
        font-size: 34px;
    }

    /*添加分类按钮  row*/
    .add_btn{
        margin-top: 10px;
        margin-bottom: 23px;
    }
    /*类别的整个列表*/
    .list{
        padding-left: 25px;
        border-radius: 10px;
    }
</style>